from __future__ import print_function, absolute_import

import time
from datetime import datetime, timedelta

from gm.api import *
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib

from tools import dbTool
from run.gm.gmTool import gmTool
from tools.selectStockTool import selectStockTool


def evalFirstPrice(context):
    # code = 'SZSE.159531'
    for code in selectStockTool.getSmallIndexStock():
        upAllPredict = 0
        downAllPredict = 0
        upRightPredict = 0
        downRightPredict = 0
        now = context.now
        todayStr = now.strftime('%Y-%m-%d')
        todayPrice = history(symbol=code, frequency='1d', start_time=todayStr, end_time=todayStr,
                             fields='open, close, low, high, eob', adjust=ADJUST_PREV, df=True)
        todayPrice = todayPrice.iloc[0]
        sign = gmTool.monitorIndexTrend(context)
        if sign != 0:
            if sign == 1:
                upAllPredict += 1
                if todayPrice['open'] < todayPrice['close']:
                    upRightPredict += 1
            if sign == -1:
                downAllPredict += 1
                if todayPrice['open'] > todayPrice['close']:
                    downRightPredict += 1

        result = {'code': code, 'up_all': upAllPredict, 'up_right': upRightPredict,
                  'down_all': downRightPredict, 'down_right': downRightPredict}
        result = pd.DataFrame([result])
        # 保存到数据库
        dbTool.saveAll('rs_first_price', result, '评估初始行情对整日行情的影响')
        break


def test(context):
    his = history(symbol='SZSE.159531', frequency='1d', start_time='2024-12-23', end_time='2024-12-23',
                  fields='open, close, low, high, eob', adjust=ADJUST_PREV, df=True)
    pass


def init(context):
    # 每日定时任务
    # evalFirstPrice(context)
    schedule(schedule_func=evalFirstPrice, date_rule='1d', time_rule='09:32:05')
    pass


def on_bar(context, bars):
    pass


if __name__ == '__main__':
    '''
        strategy_id策略ID, 由系统生成
        filename文件名, 请与本文件名保持一致
        mode运行模式, 实时模式:MODE_LIVE 回测模式:MODE_BACKTEST
        token绑定计算机的ID, 可在系统设置-密钥管理中生成
        backtest_start_time回测开始时间
        backtest_end_time回测结束时间
        backtest_adjust股票复权方式, 不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
        backtest_initial_cash回测初始资金
        backtest_commission_ratio回测佣金比例
        backtest_slippage_ratio回测滑点比例
        backtest_match_mode市价撮合模式，以下一tick/bar开盘价撮合:0，以当前tick/bar收盘价撮合：1
        '''
    # b40aa9ba-c11d-11ef-8a13-e8c829bed8c8
    run(strategy_id='14db9d1d-bdb8-11ef-8b1c-7486e210ef39',
        filename='researchGM.py',
        mode=MODE_BACKTEST,
        token='fd322a3568282f2404e1602e95a8861fe5e36b00',
        backtest_start_time='2024-07-01 08:00:00',
        backtest_end_time='2024-12-26 16:00:00',
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=10000000,
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001,
        backtest_match_mode=1)
